import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class Serwer extends Frame implements ActionListener
{
	WindowAdapter close = new WindowAdapter()
	{
        public void windowClosing(WindowEvent e) 
		{
			if(out!=null) out.println("Q");
            System.exit(0);
        }
    };
	ServerSocket server=null;
	Socket client=null;
	PrintWriter out = null;
	Panel connectPanel, talkPanel;
	TextField txtPort, txtTalk;
	Button bConnect, bSend;
	Label lTalk;
	SrvMessenger srvMsg;
	Serwer()
	{
		connect();
		setResizable(false);
		addWindowListener(close);
	}
	void connect()
	{
		connectPanel = new Panel();
		txtPort = new TextField(10);
		bConnect = new Button("Polacz");
		bConnect.addActionListener(this);
		connectPanel.setLayout(new GridLayout(1,2));
		this.add(connectPanel);
		connectPanel.add(txtPort);
		connectPanel.add(bConnect);
		this.pack();
	}
	void talk()
	{
		talkPanel = new Panel();
		txtTalk = new TextField(20);
		bSend = new Button("Wyslij");
		bSend.addActionListener(this);
		lTalk = new Label("");
		talkPanel.setLayout(new GridLayout(3,1));
		this.add(talkPanel);
		talkPanel.add(txtTalk);
		talkPanel.add(bSend);
		talkPanel.add(lTalk);
		this.pack();
	}
	void newMessage(String message)
	{
		lTalk.setText(message);
	}
	public void actionPerformed(ActionEvent e)
	{
		try
		{
			if(e.getSource()==bConnect)
			{
				System.out.println(txtPort.getText());
				this.remove(connectPanel);
				
					talk();
					server=new ServerSocket(Integer.parseInt(txtPort.getText()));
					
					for(int i=0; i<1; i++)
					{
						client = server.accept();
						srvMsg = new SrvMessenger(client, this);
						srvMsg.start();
						System.out.println("S");
						//client = null;
					}
					//System.out.println(txtPort.getText());
			}
			if(e.getSource()==bSend)
			{
				//srvMsg.outMessage=txtTalk.getText();
				srvMsg.out.println(txtTalk.getText());
				txtTalk.setText("\0");
				lTalk.setText("\0");
			}
		}
		catch(NumberFormatException ex) {} 
		catch (IOException ex) {}
		catch(NullPointerException ex) {}
	}
	public static void main(String[] args)
	{
		Serwer s = new Serwer();
		s.setVisible(true);
	}
}
